package com.combetter.changxing.viewmodel;

import android.app.Application;
import android.support.annotation.NonNull;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.combetter.changxing.MyApp;
import com.combetter.changxing.db.AppDatabase;
import com.combetter.changxing.db.entity.Collect;
import com.combetter.changxing.model.EventMessage;
import com.combetter.changxing.net.service.APIService;
import com.combetter.changxing.util.AppManager;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.util.ToastUtils;
import com.combetter.changxing.viewmodel.base.BaseViewModel;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/6/12.
 */
public class MineCollectViewModel extends BaseViewModel {
    public List<Collect> collects1 = new ArrayList<>();

    public MineCollectViewModel(@NonNull Application application) {
        super(application);
    }

    public void back(View view) {
        AppManager.finishCurrentActivity();
    }

    /**
     * 查询已收藏的设备
     */
    public void selectCollect(SmartRefreshLayout refreshLayout) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", MyApp.getInstance().getUserInfo().getUid());
        map.put("pagenum", "1");
        map.put("pagesize", "9999");
        LogUtil.e("查询已收藏请求参数：", map);
        mHttpRequest.createService(APIService.class)
                .queryUidAllSmoke(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(throwable -> {
                    EventBus.getDefault().post(new EventMessage("selectCollect", ""));
                    refreshLayout.finishRefresh();
                })
                .subscribe(httpResult -> {
                    refreshLayout.finishRefresh();
                    LogUtil.e("查询已收藏返回：", httpResult);
                    if (httpResult.getCode() == 200) {
                        JSONObject jsonObject = new JSONObject(new Gson().toJson(httpResult.getData()));
                        String resultData = jsonObject.getString("list");
                        collects1.clear();
                        collects1 = new Gson().fromJson(resultData, new TypeToken<List<Collect>>() {
                        }.getType());

                        if (collects1 != null&&collects1.size()<=0) {
                            MyApp.getInstance().getDatabase().collectDao().deleteAll();
                        }
                        dealData(collects1);
                        EventBus.getDefault().post(new EventMessage("selectCollect", ""));
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }


    public void dealData(List<Collect> collects2) {
        AppDatabase database = MyApp.getInstance().getDatabase();
        if (database.collectDao() != null && database.collectDao().getCollectInfoList() != null && database.collectDao().getCollectInfoList().size() > 0) {
            Collect selectCollect = database.collectDao().findCollect(1);
            for (int i = 0; i < collects2.size(); i++) {
                if (selectCollect != null && collects2.get(i).getCode().equals(selectCollect.getCode())) {
                    collects2.get(i).setSelectCurrent(1);
                } else {
                    collects2.get(i).setSelectCurrent(2);
                }
            }
        }
        if (collects2.size() > 0) {
            MyApp.getInstance().getDatabase().collectDao().deleteAll();
        }
        for (Collect collect : collects2) {
            MyApp.getInstance().getDatabase().collectDao().insertSingle(collect);
        }
    }

    /**
     * 取消收藏
     */
    public void updateSmoke(int muid) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("muid", muid);
        LogUtil.e("取消收藏参数：", map);
        mHttpRequest.createService(APIService.class)
                .updateSmoke(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(httpResult -> {
                    LogUtil.e("取消收藏返回：", httpResult);
                    if (httpResult.getCode() == 200) {
                        EventBus.getDefault().post(new EventMessage("updateSmoke", ""));
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }

    /**
     * 切换当前收藏
     *
     * @param codes
     */
    public void updateType(String codes) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", MyApp.getInstance().getUserInfo().getUid());
        map.put("codes", codes);
        LogUtil.e("切换当前收藏参数：", map);
        mHttpRequest.createService(APIService.class)
                .updateType(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(httpResult -> {
                    LogUtil.e("切换当前收藏返回：", httpResult);
                    if (httpResult.getCode() == 200) {
                        ToastUtils.success("已经切换为当前品牌香烟！");
                        EventBus.getDefault().post(new EventMessage("cutCigarette", ""));
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }
}
